package com.google.code.krillion.firehose.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ResourceBundle;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.google.code.krillion.firehose.data.Friend;
import com.google.code.krillion.firehose.data.PMF;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;

public class FollowerWorkerServlet implements Servlet {
    private static final Logger log = Logger.getLogger(FollowerWorkerServlet.class.getName());
    private static ServletConfig config;
    private static String username;
    private static String password;
	private static Twitter twitter;
    private static User user;
	
	private static final String MSG_WELCOME =
		"see http://krillion-krillion.appspot.com for more information about KrillionKritter";

	@Override
	public void destroy() {
		config = null;
		username = null;
		password = null;
		user = null;
	}

	@Override
	public ServletConfig getServletConfig() {
		return config;
	}

	@Override
	public String getServletInfo() {
		return null;
	}

	@Override
	public void init(ServletConfig sc) throws ServletException {
		config = sc;
		ResourceBundle bundle = ResourceBundle.getBundle("com.google.code.krillion.firehose.server.krillion");
		username = (String) bundle.getObject("kritter.username");
		password = (String) bundle.getObject("kritter.password");
		if (username != null && password != null) {
			TwitterFactory factory = new TwitterFactory();
		    twitter = factory.getInstance(username,password);
			try {
				user = twitter.verifyCredentials();
			} catch (TwitterException e) {
				user = null;
				log.severe("TwitterException verifying user credentials: " + e.getMessage());
			}
		}
	}

	@Override
	public void service(ServletRequest req, ServletResponse resp)
			throws ServletException, IOException {
		
		String id = req.getParameter("id");
        
		resp.setContentType("text/plain");
		PrintWriter writer = resp.getWriter();
		try {
	        writer.println("ID:" + id);
			if (!twitter.existsFriendship(user.getScreenName(), id)) {
		        twitter.createFriendship(id);
		        log.info("created friendship with " + id);
			} else {
		        log.info("already friends with " + id);
			}
			// Lookup friend record in our datastore, create one when
			// one does not exist already.
			PersistenceManager pm = PMF.get().getPersistenceManager();
		    Query query = pm.newQuery(Friend.class);
		    query.setFilter("friendId == id");
		    query.declareParameters("String id");
		    query.setUnique(true);
		    try {
				Friend friend = (Friend) query.execute(id);
				if (friend == null) {
			        User follower = twitter.showUser(id);
					friend = new Friend(id, follower.getScreenName());
		            pm.makePersistent(friend);
			        twitter.sendDirectMessage(friend.getFriendName(), MSG_WELCOME);
			        log.info("Sent welcome message to " + friend.getFriendName());
				}
		    } finally {
		    	query.closeAll();
	            pm.close();
		    }
		} catch (TwitterException e) {
			log.severe("TwitterException processing new follower: " + e.getMessage());
		}
        writer.flush();
		writer.close();
	}

}
